﻿using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WebMvcDemo
{
    /// <summary>
    /// 创建PDF绘图文件
    /// </summary>
    public class ItextPdfMaker
    {
        /// <summary>
        /// 导出PDF文件
        /// </summary>
        /// <returns></returns>
        public byte[] ExportToPdf()
        {
            Console.WriteLine($"{DateTime.Now}, iText开始导出PDF");

            using MemoryStream stream = new MemoryStream();

            //初始化一个Document类实例，创建纸张大小的画布，A4尺寸 = 210 X 297 mm，= 595 x 842，设置页边距全0，整个页面全部作为画布
            var document = new Document(PageSize.A4, 0, 0, 0, 0);

            //必须先获取PdfWriter，然后document.Open，如果交换顺序，报错Document not open
            PdfWriter writer = PdfWriter.GetInstance(document, stream);

            document.AddAuthor("ItextPdfMaker");
            document.AddCreator("ItextPdfMaker");

            document.Open();

            var canvas = writer.DirectContent;

            var textfont = new Font(ItextChinaFont.ChinaFont)
            {
                Color = BaseColor.Black,
                Size = 24
            };

            string msg = $"{DateTimeOffset.Now:T}, 还有1万行iText绘图代码...";
            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(msg, textfont), 0, canvas.PdfDocument.Top - 30, 0);

            var lineColor = (DateTimeOffset.Now.Second % 4 <= 1) ? BaseColor.Red : BaseColor.Green;

            canvas.SetColorStroke(lineColor);

            canvas.SetLineWidth(3);

            //左边-底部-右边-顶部
            canvas.Rectangle(10, canvas.PdfDocument.Top - (PageSize.A4.Height - 60), PageSize.A4.Width - 20, canvas.PdfDocument.Top - 120);

            canvas.Stroke();

            msg += $", lineColor={lineColor.ToArgb():X2}, CanvasSize={PageSize.A4}";
            Console.WriteLine(msg);

            //结束一页内容
            //document.NewPage();

            //结束文档内容
            document.Close();

            byte[] ary = stream.ToArray();

            return ary;
        }
    }
}
